package com.bsoft.gol.hbs.service.impl;

import com.alibaba.fastjson.JSON;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import com.bsoft.gol.hbs.dao.PcnBaseHpiDAO;
import com.bsoft.gol.hbs.dao.PcnHpiTypeDAO;
import hcn.bean.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.bean.hpi.PcnBaseHpi;
import pcn.bean.hpi.PcnHpiType;
import pcn.enums.OperationTypeEmun;
import pcn.enums.ViewStatus;
import pcn.service.hpi.WebPcnHpiService;
import pcn.vo.hpi.PcnHpiTypeVO;
import pcn.vo.web.PcnResponse;
import service.rpc.impl.BaseUserManageUnitImpl;
import service.rpc.impl.PcnOperLogServiceImpl;
import com.bsoft.gol.hbs.utils.CommonUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 健康指标和健康类型相关api提供服务
 * 这块主要针对后台的
 *
 * @author BsoftWang
 */
@SsdevService("webPcnHpiService")
public class WebPcnHpiServiceImpl implements WebPcnHpiService {
	private final Logger logger = LoggerFactory.getLogger(WebPcnHpiServiceImpl.class);
	@Autowired
	private PcnBaseHpiDAO pcnBaseHpiDAO;
	@Autowired
	private PcnHpiTypeDAO pcnHpiTypeDAO;

	@Autowired
	private PcnOperLogServiceImpl pcnOperLogService;

	@Autowired
	private BaseUserManageUnitImpl baseUserManageUnitService;

	/**
	 * web端批量添加健康指标
	 *
	 * @param pcnBaseHpis
	 * @return
	 * @throws ControllerException
	 */
	@RpcService
	@Override
	public PcnResponse<?> pcnBaseHpiBatchAdd(List<PcnBaseHpi> pcnBaseHpis) throws ControllerException {
		for (PcnBaseHpi pcnBaseHpi : pcnBaseHpis) {
			if (StringUtils.isBlank(pcnBaseHpi.getHpiName()) ||
					StringUtils.isBlank(pcnBaseHpi.getLowerLimit()) ||
					StringUtils.isBlank(pcnBaseHpi.getUpperLimit()) ||
					StringUtils.isBlank(pcnBaseHpi.getHpiUnit())) {
				logger.warn("arg is null!" + JSON.toJSONString(pcnBaseHpi));
				continue;
			}
			savePcnBaseHpiBatch(pcnBaseHpi);
		}
		return new PcnResponse<String>().success();
	}

	/**
	 * 提交健康指标(后台)
	 *
	 * @throws ControllerException
	 */
	@RpcService
	@Override
	public PcnResponse<?> pcnBaseHpiAdd(PcnBaseHpi pcnBaseHpi) throws ControllerException {
		if (pcnBaseHpi == null) {

			throw new ControllerException("pcnBaseHpi not be null!");
		}
		if (StringUtils.isBlank(pcnBaseHpi.getHpiName())) {
			throw new ControllerException("hpiName not be null!");
		}
		if (StringUtils.isBlank(pcnBaseHpi.getLowerLimit())) {
			throw new ControllerException("lowerLimit not be null!");
		}

		if (StringUtils.isBlank(pcnBaseHpi.getUpperLimit())) {
			throw new ControllerException("upperLimit not be null!");
		}
		if (StringUtils.isBlank(pcnBaseHpi.getHpiUnit())) {
			throw new ControllerException("hpiUnit not be null!");
		}
		savePcnBaseHpiBatch(pcnBaseHpi);
		return new PcnResponse<String>().success();
	}


	/**
	 * 获取健康指标列表
	 *
	 * @param typeId 健康指票类型id
	 * @return
	 * @throws ControllerException
	 */
	@RpcService
	@Override
	public List<PcnBaseHpi> pcnBaseHpiByTypeId(Integer typeId) throws ControllerException {
		if (typeId == null) {
			throw new ControllerException("typeId is null!");
		}
		List<PcnBaseHpi> list = pcnBaseHpiDAO.findPcnBasehpiByTypeId(typeId);
		return list;
	}


	/**
	 * 健康指标类型添加
	 *
	 * @param pcnHpiType
	 * @return
	 * @throws ControllerException
	 */
	@RpcService
	@Override
	public void pcnHpiTypeAdd(PcnHpiType pcnHpiType) throws ControllerException {
		if (pcnHpiType == null) {
			throw new ControllerException("added objec not be null!");
		}

		if (pcnHpiType.getStatus() == null) {
			throw new ControllerException("status not be null!");
		}

		if (StringUtils.isBlank(pcnHpiType.getTypeCode())) {
			throw new ControllerException("typeCode not be null!");
		}

		if (StringUtils.isBlank(pcnHpiType.getTypeName())) {
			throw new ControllerException("typeName not be null!");
		}
		//获取当前用户信息
		UserVo userIdByOnline = baseUserManageUnitService.getUserIdByOnline();
		if (pcnHpiType.getTypeId() == null) {
			if (pcnHpiTypeDAO.getPcnHpiTypeByCode(pcnHpiType.getTypeCode()) != null) {
				throw new ControllerException("typeCode " + pcnHpiType.getTypeCode() + "  already exists!");
			}
			pcnHpiType.setTenantId(userIdByOnline.getTenantId());
			pcnHpiType.setCreateUser(userIdByOnline.getUserId());
			pcnHpiType.setCreateDt(new Date());
			pcnHpiTypeDAO.save(pcnHpiType);
			//保存到记录表
			pcnOperLogService.saveInfo(pcnHpiType.getTypeName(), OperationTypeEmun.add.getName(), pcnHpiType.getTypeId().toString(), "系统配置-健康指标");
		} else {
			PcnHpiType old = pcnHpiTypeDAO.get(pcnHpiType.getTypeId());
			if (old == null) {
				throw new ControllerException(500, "update fail ! TypeId " + pcnHpiType.getTypeId() + " not exists!");
			}
			PcnHpiType typeExsits = pcnHpiTypeDAO.getPcnHpiTypeByCode(pcnHpiType.getTypeCode());
			if (typeExsits != null && !typeExsits.getTypeId().equals(old.getTypeId())) {
				throw new ControllerException(504, "typeCode " + pcnHpiType.getTypeCode() + " alreay exists!");
			}
			old.setStatus(pcnHpiType.getStatus());
			old.setTypeCode(pcnHpiType.getTypeCode());
			old.setTypeName(pcnHpiType.getTypeName());
			old.setLastModifyDt(new Date());
			old.setLastModifyUser(userIdByOnline.getUserId());
			pcnHpiTypeDAO.update(old);

			//保存到记录表
			pcnOperLogService.saveInfo(pcnHpiType.getTypeName(), OperationTypeEmun.update.getName(), pcnHpiType.getTypeId().toString(), "系统配置-健康指标");
		}
	}


	/**
	 * 健康指标类型列表
	 *
	 * @return
	 */
	@RpcService
	@Override
	public List<PcnHpiTypeVO> pcnHpiTypeList() {
		List<PcnHpiType> list = pcnHpiTypeDAO.findPcnHpiTypes();
		List<PcnHpiTypeVO> vos = new ArrayList<>();
		for (PcnHpiType type : list) {
			vos.add(toHcnHpiTypeVO(type));
		}
		return vos;
	}

	/**
	 * 删除健康指标类型
	 *
	 * @throws ControllerException
	 */
	@Override
	@RpcService
	public void deleteHpiType(PcnHpiType pcnHpiType) throws ControllerException {
		if (CommonUtils.isEmpty(pcnHpiType.getTypeId())) {
			throw new ControllerException("健康指标类型id不可为空");
		}
		//判断指标是否被使用
		List<PcnBaseHpi> pcnBaseHpiList = pcnBaseHpiDAO.findPcnBasehpiByTypeId(pcnHpiType.getTypeId());
		if (CommonUtils.isNotEmpty(pcnBaseHpiList)) {
			throw new ControllerException("不可删除，健康指标类型已经在使用");
		}
		//没有健康指标，则直接删除
		pcnHpiTypeDAO.updateBaseHpiType(pcnHpiType.getTypeId());
	}

	/**
	 * 删除健康指标
	 *
	 * @throws ControllerException
	 */
	@Override
	@RpcService
	public void deleteHpi(PcnBaseHpi pcnBaseHpi) throws ControllerException {
		if (CommonUtils.isEmpty(pcnBaseHpi.getHpiId())) {
			throw new ControllerException("健康指标id不可为空");
		}
		//删除健康指标
		pcnBaseHpiDAO.updateBaseHpi(pcnBaseHpi.getHpiId());
	}

	private PcnHpiTypeVO toHcnHpiTypeVO(PcnHpiType hcnHpiType) {
		PcnHpiTypeVO vo = new PcnHpiTypeVO();
		BeanUtils.copyProperties(hcnHpiType, vo);
		return vo;
	}


	private void savePcnBaseHpiBatch(PcnBaseHpi pcnBaseHpi) throws ControllerException {
		//获取当前用户信息
		UserVo userIdByOnline = baseUserManageUnitService.getUserIdByOnline();
		//判断类型有没有
		if (pcnHpiTypeDAO.get(pcnBaseHpi.getTypeId()) == null) {
			throw new ControllerException("typeId " + pcnBaseHpi.getTypeId() + " not exists!");
		}

		if (pcnBaseHpi.getHpiId() == null) {

			if (pcnBaseHpi.getStatus() == null) {
				pcnBaseHpi.setStatus(ViewStatus.enable.getValue());
			}

			//判断code是否已经存在
			if (pcnBaseHpiDAO.findPcnBasehpiByHpiCode(pcnBaseHpi.getHpiCode()).size() > 0) {
				throw new ControllerException(502, "add fail! hpiCode " + pcnBaseHpi.getHpiCode() + " alreay exists! ");
			}
			pcnBaseHpi.setTenantId(userIdByOnline.getTenantId());
			pcnBaseHpi.setCreateUser(userIdByOnline.getUserId());
			pcnBaseHpi.setCreateDt(new Date());
			pcnBaseHpiDAO.save(pcnBaseHpi);
		} else {
			List<PcnBaseHpi> pcnBaseHpiExsists = pcnBaseHpiDAO.findPcnBasehpiByHpiCode(pcnBaseHpi.getHpiCode());
			//判断健康指标code是否已经存在,因为是修改，所以要排除和自己相等
			if (pcnBaseHpiExsists.size() > 0 && !pcnBaseHpiExsists.get(0).getHpiId().equals(pcnBaseHpi.getHpiId())) {
				throw new ControllerException(501, "hpiCode " + pcnBaseHpi.getHpiCode() + " alreay exists!");
			}
			pcnBaseHpi.setLastModifyUser(userIdByOnline.getUserId());
			pcnBaseHpi.setLastModifyDt(new Date());
			PcnBaseHpi oldEl = pcnBaseHpiDAO.get(pcnBaseHpi.getHpiId());
			if (oldEl == null) {
				throw new ControllerException("illegal arg,HpiId " + pcnBaseHpi.getHpiId() + " not exists!");
			}
			BeanUtils.copyProperties(pcnBaseHpi, oldEl, new String[]{"tenantId", "createUser", "createDt", "hpiId"});
			pcnBaseHpiDAO.update(oldEl);
		}
	}


}
